package com.cloud.service;

import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.cloud.common.constants.ExcelPoiConstants;
import com.cloud.exception.CustomException;
import com.cloud.utils.ExportUtils;
import com.cloud.utils.ServletUtils;
import com.cloud.utils.WordUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Word 文档操作
 *
 * @author yzj
 */
@Component
public class EasyPoiService {

    @Resource
    private FeignAnnexService feignAnnexService;

    /**
     * 操作Word07 文档
     *
     * @param fileNames 上传Word07 文件对象名称列表
     * @param dataMap      设置数据参数
     */
    public void setWordReplaceAssign(List<String> fileNames, Map<String, Object> dataMap) {
        try {
            HttpServletResponse response = ServletUtils.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=template.doc");
            List<String> srcDocList = new ArrayList<>();
            for (String fileName : fileNames) {
                // 获取存储服务器文件路径
                String fileUrl = feignAnnexService.getInAnnexUrl(fileName).getData();
                if (StringUtils.isEmpty(fileUrl)) {
                    throw new CustomException("操作失败：文件地址不存在");
                }
            }
            OutputStream outputStream = response.getOutputStream();
            File tempFile = File.createTempFile("tempDoc", ExcelPoiConstants.Word_Suffix);
            XWPFDocument document = null;
            if (srcDocList.size() < 2) {
                document = WordExportUtil.exportWord07(srcDocList.get(0), dataMap);
            } else {
                List<XWPFDocument> docList = new ArrayList<>();
                for (String srcDoc : srcDocList) {
                    docList.add(WordExportUtil.exportWord07(srcDoc, dataMap));
                }
                // 合并后的Word07文档对象,输出到File对象
                document = WordUtils.setMergeWord(docList);
            }
            ExportUtils.wordExport(document, outputStream, tempFile);
        } catch (Exception e) {
            throw new CustomException("操作失败：" + e);
        }
    }

    /**
     * 生成并下载 Word07模板
     */
    public void getWord07Template() {
        try {
            HttpServletResponse response = ServletUtils.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=template.doc");
            XWPFDocument document = new XWPFDocument();
            OutputStream outputStream = response.getOutputStream();
            // Word文档对象转Pdf并输出到浏览器
            document.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            throw new CustomException("操作失败：" + e);
        }
    }

    /**
     * 操作 Excel07文档下载
     *
     * @param fileName 上传Excel07 文件对象名称
     * @param dataMap  设置数据参数
     */
    public void setExcelReplaceAssign(String fileName, Map<String, Object> dataMap) {
        try {
            HttpServletResponse response = ServletUtils.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=template.xls");
            // 获取存储服务器文件路径
            String srcExcelUrl = feignAnnexService.getInAnnexUrl(fileName).getData();
            if (StringUtils.isEmpty(srcExcelUrl)) {
                throw new CustomException("操作失败：文件地址不存在");
            }
            OutputStream outputStream = response.getOutputStream();
            File tempFile = File.createTempFile("tempXls", ExcelPoiConstants.Excel_Suffix);
            ExportUtils.excelExport(srcExcelUrl, dataMap, tempFile);
            InputStream file = new FileInputStream(tempFile);
            ServletUtils.writeIO(file, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 预览 Excel文档,转 HTML
     *
     * @param fileName
     * @param dataMap
     */
    public void selExcelToHtml(String fileName, Map<String, Object> dataMap) {
        try {
            HttpServletResponse response = ServletUtils.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "text/html; charset=UTF-8");
            // 获取存储服务器文件路径
            String srcExcelUrl = feignAnnexService.getInAnnexUrl(fileName).getData();
            if (StringUtils.isEmpty(srcExcelUrl)) {
                throw new CustomException("操作失败：文件地址不存在");
            }
            Workbook workbook = ExportUtils.excelToHtml(srcExcelUrl, dataMap);
            ExcelToHtmlParams params = new ExcelToHtmlParams(workbook, true, "yes");
            response.getOutputStream().write(ExcelXorHtmlUtil.excelToHtml(params).getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
